from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

from .database import Base


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    email = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)

    items = relationship("Item", back_populates="owner")


class Item(Base):
    __tablename__ = "items"
    id = Column(Integer, primary_key=True)
    title = Column(String, index=True)
    description = Column(String, index=True)
    owner_id = Column(Integer, ForeignKey("users.id"))
    owner = relationship("User", back_populates="items")


# 角色表
class Role(Base):
    __tablename__ = "role"
    id = Column(Integer, primary_key=True)
    role_name = Column(String, unique=True, index=True)
    order = Column(Integer, default=1)
    status = Column(Boolean, default=True)


class Menu(Base):
    __tablename__ = "menu"
    id = Column(Integer, primary_key=True, comment="主键")
    menu_name = Column(String, unique=True, index=True, comment="菜单名称")
    parent_id = Column(Integer, default=1, comment="上级ID")
    order_num = Column(Integer, default=1, comment="排序")
    path = Column(String, default="", comment="路由地址")
    component = Column(String, default="", comment="组件路径")
    menu_type = Column(String, default="", comment="菜单类型（M目录 C菜单, L外链）")
    visible = Column(String, default="", comment="菜单状态（0显示 1隐藏）")
    perms = Column(String, default="", comment="权限标识")
    icon = Column(String, default="", comment="菜单图标")
    is_frame = Column(String, default="", comment="是否为外链（0是 1否）")
    is_cache = Column(Boolean, default=True, comment="缓存")
    status = Column(Boolean, default=True, comment="状态")


#########################################
# 网关节点表
#########################################
class GeetestNode(Base):
    __tablename__ = "geetest_node"

    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    node_tag = Column(String)
    ip_address = Column(String, unique=False)
    protocol = Column(String, nullable=False, default="http")
    port = Column(String, nullable=False, default="80")
    # 0（已上传到服务器），1(上传成功)，2(上传失败）
    status_result = Column(String, nullable=False, default="0")
    # 是否启用
    enable_status = Column(Boolean, nullable=False, default=True)
    protect_sha1 = Column(String, nullable=False, default="")
    # create_time = Column(DateTime, nullable=False, server_default=func.now())
    # update_time = Column(DateTime, nullable=False)

    def to_dict(self):
        res_dcit = {}
        for item in self.__table__.columns:
            item_key = item.name
            item_value = getattr(self, item.name, None)
            if item_key in ["create_time", "update_time"]:
                res_dcit[item_key] = item_value.strftime("%Y-%m-%d %H:%M:%S")
            else:
                res_dcit[item_key] = item_value
        return res_dcit